package com.sailors.common.task.sdk.core.handle.worker;

import com.sailors.common.task.sdk.core.handle.factory.FileTaskHandler;
import com.sailors.common.task.sdk.core.handle.factory.HandlerFactory;
import com.sailors.common.task.sdk.core.model.FileTaskFailedDto;
import com.sailors.common.task.sdk.core.model.RefreshProcessDto;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Task worker
 *
 * @description: SDK守护线程，异步监控任务进度及结果
 * @author: cyj
 * @date 2022 -11-25 14:56:10
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@Slf4j
public class TaskWorker {

    /**
     * OFF
     */
    private static final AtomicBoolean ON_OFF = new AtomicBoolean(false);

    /**
     * Start
     */
    public static void start() {
        // 只能启动一次
        if (ON_OFF.compareAndSet(false, true)) {
            // 任务监视
            processWatch();
            // 任务失败监视
            failedWatch();
        }
    }

    /**
     * Failed watch
     */
    private static void failedWatch() {
        new Thread(() -> {
            while (true) {
                try {
                    FileTaskFailedDto fileTaskFailedDto = TaskContainer.FAILED_EXECUTE_QUEUE.take();
                    HandlerFactory.getInstance(FileTaskHandler.class).failedAsync(fileTaskFailedDto);
                } catch (Exception e) {
                    log.warn("TaskContainer.FAILED_EXECUTE_QUEUE take execute failed:{}", e.getMessage());
                }
            }
        }).start();
    }

    /**
     * Process watch
     */
    private static void processWatch() {
        new Thread(() -> {
            while (true) {
                try {
                    RefreshProcessDto refreshProcessDto = TaskContainer.REFRESH_PROCESS_EXECUTE_QUEUE.take();
                    HandlerFactory.getInstance(FileTaskHandler.class).refreshProcessAsync(refreshProcessDto);
                } catch (Exception e) {
                    log.warn("TaskContainer.REFRESH_PROCESS_EXECUTE_QUEUE take execute failed:{}", e.getMessage());
                }
            }
        }).start();
    }

}
